<!--
 * @Author: licc
 * @Date: 2020-11-11 11:11:11
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-11-13 15:45:50
-->
<template>
  <div class="ticket">
    <el-row>
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="handleSearchFunc"></QuickSearch>
    </el-row>
    <el-row class="ticket-data-page">
      <el-row :id="'apassMicroTicketData_' + moduleType" class="page-container mp-micro" />
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { loadMicroApp } from 'qiankun'
import { CommonModule } from '@/store/modules/common'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
// import { SheetRecordModule } from '@/store/modules/ticketMicAppStore/sheetRecord'
@Component({
  name: 'Ticket',
  components: { QuickSearch }
})
export default class Ticket extends Vue {
  [x: string]: any
  @Prop({ default: {} }) private commonData!: any
  @Prop({ default: '' }) private moduleType!: string // 每个模块的微前端ID

  private quickSearchForm: any = {} // 快捷搜索表单 需动态变化
  private ticketMicApp: any
  private ticketMicAppStore: any = {
    hiddenHeader: true, // 隐藏一些东西
    recordId: '', // 客户Id ==> 一条数据的id，工单目前不需要默认回显
    applicationId: this.$store.state.common.mpInfo.mpApplicationId, // 应用id
    worksheetId: '' // 工单模板id
  }

  private beforeDestroy () { // 组件销毁时，清除定时器和事件总线
    this.$bus.$off('initSummaryTicket')
  }

  @Watch('commonData', { immediate: true })
  private commonDataChange (newData) {
    this.initQianKunTicket()
    // this.ticketMicAppStore.recordId = (typeof newData === 'object' && newData.id) ? newData.id : ''
  }

  // 查询
  private handleSearchFunc (form) {
    this.ticketMicAppStore.worksheetId = this.quickSearchForm.form.worksheetId
    this.initMicroApp()
  }

  private initQianKunTicket () {
    // 获取工单模板列表缓存，右侧工单弹屏的选择框用
    CommonModule.getMpInfo({ url: '/auth/get/mp/relation', method: 'POST', data: {} }).then((res: any) => {
      this.$getCache('/crm/action/ticket/cache', ['ticketList'], false).then((data: any) => {
        this.quickSearchForm = { // 高级搜索数据
          form: {
            worksheetId: data.ticketList.length > 0 ? data.ticketList[0].worksheetId : ''
          },
          advSearchOptions: [ // 高级搜索数据
            { label: '工单模板', name: 'worksheetId', inputType: 'select', clearable: false, selectData: data.ticketList, placeholder: '工单模板', defaultProp: { label: 'name', value: 'worksheetId' } }
          ]
        }
        if (data.ticketList.length > 0) {
          this.ticketMicAppStore.worksheetId = data.ticketList[0].worksheetId
          this.initMicroApp()
        }
      })
    })
  }

  private initMicroApp () {
    if (this.ticketMicAppStore.worksheetId === '') { // 必须选择一个模板
      console.log('还没选择工单模板，初始化失败')
      // this.unmountMicroApp()
      return false
    }
    if (!this.ticketMicAppStore.applicationId) {
      this.ticketMicAppStore.applicationId = this.$store.state.common.mpInfo.mpApplicationId
    }
    const store = this.ticketMicAppStore
    this.$set(store, 'handleSaveFunc', (type, that, data) => {
      if (type === 'add') { // 新增工单后进行回显
        that.initForm(data, true) // mp的回调
      }
    })
    if (this.ticketMicApp && JSON.stringify(this.ticketMicApp) !== '{}') {
      this.ticketMicApp.mountPromise.then(() => {
        this.ticketMicApp.update({
          type: 'changeRecord',
          data: store
        })
      })
    } else { // 第一次创建
      this.ticketMicApp = loadMicroApp(
        {
          name: 'apass-micro-ticketData',
          entry: `${(CommonModule.initConfig as any).platformConfig.mopowerUrl}/sheetRecord.html`,
          container: `#apassMicroTicketData_${this.moduleType}`,
          props: {
            routerBase: this.$router.currentRoute.path,
            store,
            user: {
              id: this.$store.state.common.mpInfo.mpUserId,
              companyId: this.$store.state.common.mpInfo.mpCompanyId
            }
          }
        },
        {
          sandbox: {
            // experimentalStyleIsolation: true
          }
        }
      )
      // 因为第一次加载比较慢，防止失败所以在timeout之后再修改一次
      // this.changeQianKunDom()
      // setTimeout(() => {
      //   this.changeQianKunDom()
      // }, 1000)
    }
  }

  private unmountMicroApp () {
    if (this.ticketMicApp && JSON.stringify(this.ticketMicApp) !== '{}') {
      this.ticketMicApp.mountPromise.then(() => {
        this.ticketMicApp.unmount()
      })
    }
  }

  private changeQianKunDom () {
    if ((document as any).getElementsByClassName('drawer-main')[0]) {
      (document as any).getElementsByClassName('drawer-main')[0].style['border-radius'] = '10px'
    }
  }
}
</script>

<style lang="stylus" scoped>
.ticket
  height 100%
  overflow auto
.ticket-data-page
  height calc(100% - 78px)
  overflow auto
  & >>> .el-form-item--mini .el-form-item__label
    font-size 14px
  .page-container
    height 100%
    background white url('../../../assets/img/loading.gif') no-repeat center center
    background-size 1.2 1.2
</style>
